package cn.pzhu.javaee.webapp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.pzhu.javaee.webapp.context.WebAppConstant;
import cn.pzhu.javaee.webapp.context.WebAppContext;
import cn.pzhu.javaee.webapp.exception.WebAppBusinessException;
import cn.pzhu.javaee.webapp.exception.WebAppException;
import cn.pzhu.javaee.webapp.exception.WebAppSysException;
import cn.pzhu.javaee.webapp.utils.JsonMapper;


/**
 * Servlet implementation class WebAppBaseServlet
 */

public class WebAppBaseServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	protected Logger log=LoggerFactory.getLogger(this.getClass());
	
	public static final String ACTION_TAG = "action";
	public static final String ACTION_METHOD_PREX = "action";
	public static final String DEFAULT_ACTION = "index";
	public static final String JSON_TAG = "json";
	public static final String JSON_METHOD_PREX = "json";
	
       
    
    public WebAppBaseServlet() {
        super();
    }
    
    @Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		try {
			super.service(request, response);

		} catch (WebAppException wae) {
			log.error("WebApp Error:" + wae.getMessage());
			request.setAttribute("Error", wae.getMessage());
			wae.printStackTrace();
			forward(request, response, WebAppConstant.WebApp_ErrorPage);

		} catch (Exception e) {
			log.error("System Erro:\n" + e.getMessage());
			e.printStackTrace();
			request.setAttribute("Error", e.getMessage());
			forward(request, response, WebAppConstant.WebApp_ErrorPage);
		}		

	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action=request.getParameter(ACTION_TAG);
		String json=request.getParameter(JSON_TAG);
		if(StringUtils.isNotBlank(action)){
			doAction(request, response,action);
		}else if(StringUtils.isNotBlank(json)){
			doJson(request,response,json);
		}else{
			doAction(request, response,DEFAULT_ACTION);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action=request.getParameter(ACTION_TAG);
		String json=request.getParameter(JSON_TAG);
		if(StringUtils.isNotBlank(action)){
			doAction(request, response,action);
		}
		if(StringUtils.isNotBlank(json)){
			doJson(request, response,json);
		}
	}
	protected void doAction(HttpServletRequest request, HttpServletResponse response,String action)
			throws ServletException, IOException {
		log.debug("Action:"+action);
		String methodName=ACTION_METHOD_PREX+action.substring(0, 1).toUpperCase()+action.substring(1);
		Object[] params={request,response};
		try {
			MethodUtils.invokeMethod(this, methodName, params);
		} catch (NoSuchMethodException e) {			
			log.error(e.getMessage());
			//e.printStackTrace();
			throw new WebAppSysException(methodName+"is not existed.");
		} catch (Exception e) {
			log.error(e.getMessage());
			//e.printStackTrace();
			throw new WebAppSysException(methodName+"　调用异常");	
		} 
	}
	protected void doJson(HttpServletRequest request, HttpServletResponse response,String json)
			throws ServletException, IOException {
		log.debug("Json:"+json);		
		String methodName=JSON_METHOD_PREX+json.substring(0, 1).toUpperCase()+json.substring(1);
		log.debug("methodName:"+methodName);
		Object[] params={request,response};
		try {
			MethodUtils.invokeMethod(this, methodName, params);
		} catch (NoSuchMethodException e) {			
			log.error(e.getMessage());
			//e.printStackTrace();
			throw new WebAppSysException(methodName+"is not existed.");
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			throw new WebAppSysException(methodName+"　调用异常");	
		} 
	}
	protected void sendJson(HttpServletResponse response, Object jsonResult)
			throws IOException {
		String json = JsonMapper.getInstance().toJson(jsonResult);
		if(log.isDebugEnabled()){
			log.debug("=============JSON==============\n"+json);
		}
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out=response.getWriter();
		out.print(json);
		out.close();
	}
	protected void sendPlainText(HttpServletResponse response,Object plainTextObject) throws IOException{
		if(log.isDebugEnabled()){
			log.debug("=============Plain Text==============\n"+plainTextObject.toString());
		}
		response.setContentType("text/plain"); 
		response.setCharacterEncoding("UTF-8");
		PrintWriter out=response.getWriter();
		out.write(plainTextObject.toString());
	}
	protected void sendJavascript(HttpServletResponse response,Object jscriptObject) throws IOException{
		if(log.isDebugEnabled()){
			log.debug("=============Script==============\n"+jscriptObject.toString());
		}
		response.setContentType("application/x-javascript"); 
		response.setCharacterEncoding("UTF-8");
		PrintWriter out=response.getWriter();
		out.write(jscriptObject.toString());
	}

	protected void forward(HttpServletRequest request,
			HttpServletResponse response, String url) throws ServletException,
			IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}
	protected void include(HttpServletRequest request,
			HttpServletResponse response, String url) throws ServletException,
			IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.include(request, response);
	}
	protected void redirect(HttpServletResponse response, String url)
			throws IOException {
		response.sendRedirect(url);
	}
	protected String getCNParam(HttpServletRequest request,String name){
		String value=request.getParameter(name);
		value=value==null?null:converToUTF8(value);
		return value;
		
	}
	protected String converToUTF8(String source){
		String destStr=null;
		try {
			destStr=new String(source.trim().getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {		
			e.printStackTrace();
		}
		return destStr;
	}
	protected String getRealPath(HttpServletRequest request, String path) {
		ServletContext application = request.getSession().getServletContext();
		String str = application.getRealPath(path);
		return str;
	}
	/*---读取request参数------------*/
	protected String getString(HttpServletRequest request,String paramName){
		String pv=request.getParameter(paramName);
		log.debug("PARAM:"+paramName +"="+pv);
		if(StringUtils.isBlank(pv)){
			return null;
		}else{
			return pv;
		}
		
	}
	protected String[] getStringArray(HttpServletRequest request,String paramName){
		String[] pvs=request.getParameterValues(paramName);
		if(pvs==null||pvs.length==0){
			return null;
		}
		return pvs;
	}
	protected int[] getIntArray(HttpServletRequest request,String paramName){
		String[] pvs=request.getParameterValues(paramName);
		if(pvs==null||pvs.length==0){
			return null;
		}
		int[] datas=new int[pvs.length];
		for(int i=0;i<pvs.length;i++){
			datas[i]=Integer.parseInt(pvs[i]);
		}
		return datas;
	}
	
	protected Integer getInt(HttpServletRequest request,String paramName){
		String pvStr=request.getParameter(paramName);
		Integer pv=null;
		if(StringUtils.isBlank(pvStr)){
			return null;
		}else{
			try{
				pv=Integer.parseInt(pvStr);
			}catch(NumberFormatException e){
				e.printStackTrace();
			}
		}
		return pv;
	}
	protected Long getLong(HttpServletRequest request,String paramName){
		String pvStr=request.getParameter(paramName);
		Long pv=null;
		if(StringUtils.isBlank(pvStr)){
			return null;
		}else{
			try{
				pv=Long.parseLong(pvStr);
			}catch(NumberFormatException e){
				e.printStackTrace();
			}
		}
		return pv;
	}
	protected Date getDate(HttpServletRequest request,String paramName){
		return getDate(request,paramName,"yyyy-MM-dd");
	}
	
	protected Date getDate(HttpServletRequest request,String paramName,String parttern){
		Date d=null;
		String dstr=request.getParameter(paramName);
		if(dstr!=null){
			SimpleDateFormat sdf=new SimpleDateFormat(parttern);
			try {
				d=sdf.parse(dstr);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return d;
		
	}
	
	/*---end 读取request参数------------*/

	/*---异常－－－－－－－－－－－－*/
	protected void throwSysException(String msg)throws WebAppSysException{
		throw new WebAppSysException(msg);
	}
	protected void throwBusinessException(String msg)throws WebAppBusinessException{
		throw new WebAppBusinessException(msg);
	}
	/*--－end 异常－－－－－－－－－－－－*/
	
	/*-----------WebAppContext-------------*/
	protected WebAppContext getWebAppContext(){
		return WebAppContext.getWebAppContext();
	}
	protected WebAppContext getWebAppContext(HttpServletRequest request){
		return WebAppContext.getWebAppContext(request.getServletContext());
	}
	/*--END---------WebAppContext-------------*/
}
